/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 单号设置页面
 *  */
import React, { Component } from 'react'
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import styles from "./style.less";
import { Form, Select, Button, Input, Popconfirm, Row, Col, message } from 'antd';
import { connect } from 'dva'
import StandardTable from '@/components/StandardTable'
import { debounce } from 'lodash'
import ModalLimit from './components/ModalLimit.jsx'
import InfoCheck from '@/components/InfoCheck'

const FormItem = Form.Item
const Option = Select.Option

@connect(({ loading, orderNumSet, global, station }) => ({
  global,
  station,
  orderNumSet,
  getList: loading.effects['orderNumSet/getList']
}))
@Form.create()
export default class OrderNumSet extends Component {
  constructor(props) {
    super(props)
    this.state = {
      site_id: 'all',
      keywords: '',
      selectedRows: [],
      visible: false,
      record: {},
      page: 1
    }
    this.columns = [
      {
        title: "编号",
        dataIndex: "courier_no",
        key: "courier_no",
        align: "center",
      },
      {
        title: "所属站点",
        dataIndex: "site_name",
        key: "site_name",
        align: "center",
        render:(text, record) => {
          const { station: { company_info={} },} = this.props
          return text ? text :( company_info && company_info.brand_name)
        }
      },
      {
        title: "配送员",
        align: "center",
        render: (text, record) => {
          return `${record.courier_name}-${record.courier_phone}`
        }
      },
      {
        title: "单号获取权限",
        align: "center",
        render: (record) => {
          return (
            <>
              <span style={{marginRight:20}}>{record.is_waybill_open == '1' ? '已开启' : '已关闭'}</span>
              <Popconfirm
                placement="top"
                title={`确定${record.is_waybill_open == '1' ? '关闭' : '开启'}该业务员的单号获取权限？`}
                onConfirm={() => this.onSwitchChange(record.id, record.is_waybill_open)}
                okText="确定"
                cancelText="取消"
              >
                <Button type='primary' size='small' > {record.is_waybill_open == '1' ? '关闭' : '开启'} </Button>
              </Popconfirm>
            </>
          )
        }
      },
      {
        title: "单号限额",
        align: "center",
        render: (record) => {
          const { allowance_count } = record;
          return (
            <>
              <Button
                icon="form"
                ghost
                type="primary"
                onClick={() => this.changeModalVisible(true, record)}
                size="small"
              >
                单号限额
              </Button>
              {
                (allowance_count < 0) ? (
                  <span style={{ display: "inline-block", width: "80px", marginLeft: "20px" }}>不限</span>
                ) : (
                    <span style={{ display: "inline-block", width: "80px", marginLeft: "20px" }}>{allowance_count}</span>
                  )
              }
            </>
          )
        }
      },
    ]
  }

  handleInfoReady(data){
    if (!data.name) return;
    this.getList()
    this.getStationList(true)
  }

  getList = () => {
    const { page } = this.state
    const { dispatch } = this.props
    this.getFormVlaues(res => {
      dispatch({
        type: 'orderNumSet/getList',
        payload: {
          ...res,
          page,
          size: 20
        }
      })
    })
  }

  onSubmit = debounce( e => {
    const { dispatch } = this.props
    this.getFormVlaues(res => {
      dispatch({
        type: 'orderNumSet/getList',
        payload: {
          ...res,
          page:1,
          size: 20
        }
      })
      this.setState({page:1})
    })
  }, 500, {
    leading: true,
    trailing: false
  });

  getFormVlaues = (then) => {
    const { form } = this.props
    const { validateFields } = form
    validateFields((err, fieldsValue) => {
      if (err) return
      let values = {...fieldsValue}
      if( !fieldsValue.site_id ){
        values.site_id = 'all'
      }
      this.setState({ fieldsValue:values })
      then(values)
    })
  }

  onSwitchChange = debounce((id, checked) => {
    const { dispatch } = this.props
    dispatch({
      type: 'orderNumSet/onOff',
      payload: {
        status: checked == "1" ? "2" : "1",
        id
      }
    }).then(res => {
      this.getList()
    })
  }, 500, {
    leading: true,
    trailing: false
  })


  getStationList = (visible) => {
    const { dispatch } = this.props
    if (visible) {
      dispatch({
        type: "station/getStationList",
      });
    }
  }

  onFilterOperator = (inputValue, options) => {
    const { children } = options.props;
    if (children.indexOf(inputValue) >= 0) return true;
  };

  selectCurrency = (e, labe) => {
    this.setState({
      site_id: labe.props.value,
    })
  }

  changeSelect = (value) => {
    if (!value) {
      this.setState({
        site_id: "all",
      })
    }
  }

  onRowSelect = (selectedRows) => {
    this.setState({
      selectedRows,
    })
  }

  handleOnOffBatch(onOff) {
    const { selectedRows } = this.state
    const { dispatch } = this.props
    if (selectedRows.length == 0) {
      message.error("请先选择对应的数据再进行操作！")
      return
    }
    let id = selectedRows.map(item => item.id).join(',')
    dispatch({
      type: 'orderNumSet/onOff',
      payload: {
        status: onOff ? "1" : "2",
        id
      }
    }).then(() => {
      this.setState({ selectedRows: [] })
      this.getList()
    })
  }

  //修改限额
  changeModalVisible = (flag, record) => {
    this.setState({
      record
    });
    this.toggleModal(flag)
  };

  toggleModal = (visible) => {
    this.setState({
      visible
    })
  }

  handleTableChange = debounce(pagination => {
    this.setState({ page: pagination.current },()=>{
      this.getList()
    })
  }, 500, {
    leading: true,
    trailing: false
  });

  handleSetNumBatch = () => {
    const { selectedRows } = this.state
    if (selectedRows.length == 0) {
      message.error("请先选择对应的数据再进行操作！")
      return
    }
    let id = selectedRows.map(item => item.id).join(',')
    let record = {
      id,
      allowance_count: -1
    }
    this.changeModalVisible(true, record)
  }

  render() {
    const {
      form: { getFieldDecorator },
      getList,
      orderNumSet: { orderNumSetList },
      station: { list=[], company_info={} },
    } = this.props
    const {
      site_id,
      keywords,
      selectedRows,
      visible,
      record
    } = this.state
    return (
      <PageHeaderLayout title="单号设置">
        <InfoCheck onReady={this.handleInfoReady.bind(this)} />
        <div className={styles.main}>
          <Form layout="inline" style={{ marginBottom: "24px" }}>
            <FormItem label="公司站点">
              {
                getFieldDecorator("site_id", {
                  initialValue: site_id
                })(
                  <Select
                    filterOption={this.onFilterOperator}
                    placeholder="选择站点"
                    showSearch
                    allowClear
                    style={{ width: "250px" }}
                    onSelect={this.selectCurrency}
                    onChange={this.changeSelect}
                  >
                    <Option key="all" value="all">
                      全部站点
                    </Option>
                    <Option key="0" value="0">
                      { company_info && company_info.brand_name}
                    </Option>
                    {
                      list && list.map(({ site_id, site_name }) => (
                        <Option key={`${site_id}`} value={site_id}>
                          {site_name}
                        </Option>
                      ))
                    }
                  </Select>
                )
              }
            </FormItem>
            <FormItem label="业务员">
              {
                getFieldDecorator("search", {
                  initialValue: keywords
                })(
                  <Input
                    allowClear
                    style={{ width: 250 }}
                    placeholder="请输入业务员姓名或手机号搜索"
                  />
                )
              }
            </FormItem>
            <FormItem>
              <Button type="primary" loading={getList} onClick={this.onSubmit}>查询</Button>
            </FormItem>
          </Form>
          <StandardTable
            columns={this.columns}
            data={orderNumSetList}
            rowKey={'id'}
            selectedRows={selectedRows}
            onSelectRow={this.onRowSelect}
            onChange={this.handleTableChange}
            loading={getList}
          />
          <Row type="flex" gutter={[20, 20]} style={{ margin: 0 }}>
            <Col><a onClick={this.handleOnOffBatch.bind(this, true)}>批量开启权限</a></Col>
            <Col><a onClick={this.handleOnOffBatch.bind(this, false)}>批量关闭权限</a></Col>
            <Col><a onClick={this.handleSetNumBatch.bind(this, false)}>批量设置单号限额</a></Col>
          </Row>
          <ModalLimit
            close={this.toggleModal}
            visible={visible}
            record={record}
            getList={this.getList}
          />
        </div>
      </PageHeaderLayout>
    )
  }
}
